package com.lagou.config;

import com.lagou.pojo.Configuration;
import com.lagou.pojo.MappedStatement;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;

import java.io.InputStream;
import java.util.List;
import java.util.Map;

public class XMLMapperBuiler {

    private Configuration configuration;

    public XMLMapperBuiler(Configuration configuration) {
        this.configuration = configuration;
    }

    //解析映射文件节点封装到全局配置对象configuration中
    public void parseXMLConfig(InputStream inputStream) throws DocumentException {
        Document document = new SAXReader().read(inputStream);
        Element documentRootElement = document.getRootElement();
        List<Element> elementList = documentRootElement.elements();
        // List<Element> elementList = documentRootElement.selectNodes("//select");
        String namespace = documentRootElement.attributeValue("namespace");
        for (Element element : elementList) {
            String paramterType = element.attributeValue("paramterType");
            String id = element.attributeValue("id");
            String resultType = element.attributeValue("resultType");
            String sql = element.getTextTrim();
            MappedStatement mappedStatement = new MappedStatement();
            mappedStatement.setId(id);
            mappedStatement.setParamterType(paramterType);
            mappedStatement.setResultType(resultType);
            mappedStatement.setSql(sql);
            Map<String, MappedStatement> statementMap = configuration.getStatementMap();
            statementMap.put(namespace + "." + id, mappedStatement);
            configuration.setStatementMap(statementMap);
        }
    }
}
